<template>
  <div class="richText">
    <Toolbar
      v-if="!props.readOnly"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 100%; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, ref, onBeforeUnmount, onMounted, nextTick } from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const props = defineProps({
  textHtml: {
    type: String,
    default: "",
  },
  readOnly: {
    type: Boolean,
    default: false,
  },
});
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const mode = ref("default");
// 内容 HTML
const valueHtml = ref("");

const toolbarConfig = {
  excludeKeys: ["uploadVideo", "insertVideo", "editVideoSize", "group-video"],
};
const editorConfig = {
  placeholder: "请输入内容...",
  readOnly: props.readOnly,
  MENU_CONF: {},
};
editorConfig.MENU_CONF["uploadImage"] = {
  server: "/skr/amendFile/uploadImage",
  fieldName: "file",
  onSuccess(file, res) {
    console.log("onSuccess", file, res);
  },
};
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // console.log(editorRef.value.getAllMenuKeys());
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(() => {
  nextTick(() => {
    valueHtml.value = props.textHtml;
  });
});

defineExpose({
  valueHtml,
});
</script>

<style scoped>
.richText {
  height: 100%;
}
</style>
